package com.autorun.server.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.autorun.server.entity.Role;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 角色Mapper接口
 * 
 * @author autorun
 * @version 1.0.0
 */
@Mapper
public interface RoleMapper extends BaseMapper<Role> {

    /**
     * 根据用户ID和窗口ID获取角色
     * 
     * @param userId 用户ID
     * @param windowId 窗口ID
     * @return 角色信息
     */
    @Select("SELECT * FROM roles WHERE user_id = #{userId} AND window_id = #{windowId}")
    Role findByUserIdAndWindowId(@Param("userId") Integer userId, @Param("windowId") String windowId);

    /**
     * 根据用户ID、窗口ID和游戏获取角色
     * 
     * @param userId 用户ID
     * @param windowId 窗口ID
     * @param game 游戏名
     * @return 角色信息
     */
    @Select("SELECT * FROM roles WHERE user_id = #{userId} AND window_id = #{windowId} AND game = #{game}")
    Role findByUserIdAndWindowIdAndGame(@Param("userId") Integer userId, @Param("windowId") String windowId, @Param("game") String game);

    /**
     * 根据用户ID获取所有角色
     * 
     * @param userId 用户ID
     * @return 角色列表
     */
    @Select("SELECT * FROM roles WHERE user_id = #{userId} ORDER BY create_time DESC")
    List<Role> findByUserId(@Param("userId") Integer userId);

    /**
     * 统计用户窗口数量
     * 
     * @param userId 用户ID
     * @return 窗口数量
     */
    @Select("SELECT COUNT(*) FROM roles WHERE user_id = #{userId}")
    Integer countByUserId(@Param("userId") Integer userId);

    /**
     * 统计在线窗口数量
     * 
     * @param userId 用户ID
     * @return 在线窗口数量
     */
    @Select("SELECT COUNT(*) FROM roles WHERE user_id = #{userId} AND websocket IS NOT NULL AND websocket != ''")
    Integer countOnlineByUserId(@Param("userId") Integer userId);

    /**
     * 检查设备绑定
     * 
     * @param userId 用户ID
     * @param windowId 窗口ID
     * @return 设备ID
     */
    @Select("SELECT device_id FROM roles WHERE user_id = #{userId} AND window_id = #{windowId}")
    String findDeviceIdByUserIdAndWindowId(@Param("userId") Integer userId, @Param("windowId") String windowId);
}